package cqrtplm.aop;

import com.hustcad.plm.pdm.middle.partbom.service.TyplmPdmPartService;
import com.hustcad.plm.pdm.partbom.service.partalternate.TyplmPdmPartAlternateService;
import com.hustcad.plm.pdm.partbom.vo.AlternateInfoVO;
import com.ty.basic.entity.part.PartDO;
import com.ty.basic.response.ResponseResult;
import com.hustcad.plm.pdm.partbom.vo.PartAlterLinkVO;
import cqrtplm.mapper.DspfStatusModuleitemMapper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Aspect
@Component
public class CreateRelationshipAOP {
    @Resource
    private TyplmPdmPartService typlmPdmPartService;
    private static final Logger logger = LoggerFactory.getLogger(CreateRelationshipAOP.class);
    @Resource
    private TyplmPdmPartAlternateService typlmPartAlternateService;
    @Resource
    private DspfStatusModuleitemMapper dspfStatusModuleitemMapper;
    @Pointcut("execution(* com.hustcad.plm.pdm.partbom.controller.TyplmPartAlternateController.batchSavePartAlterLink(..))")
    public void batchSavePartAlterLinkPointcut() {}

    private final String PRODUCTSPECTRUM = "ProductSpectrum";
    private final String STATUSNAME = "状态需求模板";
    /**
     * 判断新增替代关系时  对模板生命周期的限制   只有已生效的才可以进行绑定
     * @param joinPoint
     * @return
     * @throws Throwable
     */
    @Around("batchSavePartAlterLinkPointcut()")
    public Object aroundBatchSavePartAlterLink(ProceedingJoinPoint joinPoint) throws Throwable {
        // 获取方法参数
        Object[] args = joinPoint.getArgs();
        boolean flag = true;
        boolean flag1 = true;
        if (args != null && args.length > 0 && args[0] instanceof List) {
            List<PartAlterLinkVO> partAlterLinkVOList = (List<PartAlterLinkVO>) args[0];
            // 创建全新的参数列表
            List<PartAlterLinkVO> newParamList = new ArrayList<>();
            // 遍历参数列表，获取 alternateNumber 编码
            for (PartAlterLinkVO vo : partAlterLinkVOList) {
                // 主绑定
                String alternateForNumber = vo.getAlternateForNumber();
                //被绑定
                String alternateNumber = vo.getAlternateNumber();
                if (alternateNumber == null || alternateNumber.isEmpty()) {
                    return false;
                }
                PartDO forPartDO = typlmPdmPartService.queryLastPartDoByPartNumber(alternateForNumber);
                PartDO partDO = typlmPdmPartService.queryLastPartDoByPartNumber(alternateNumber);
                String forPartTypeName = dspfStatusModuleitemMapper.selectTypeNNameByTypeoid(forPartDO.getTypeoid());
                String PartTypeName = dspfStatusModuleitemMapper.selectTypeNNameByTypeoid(partDO.getTypeoid());
                if (partDO != null && forPartDO != null) {
                    // 如果是产品型谱绑定状态需求模板，或者状态需求模板绑定产品型谱，则继续执行
                    boolean isValidCombination =
                            (forPartTypeName.equals(PRODUCTSPECTRUM) && PartTypeName.equals(STATUSNAME)) ||
                                    (forPartTypeName.equals(STATUSNAME) && PartTypeName.equals(PRODUCTSPECTRUM));

                    if (!isValidCombination) {
                        continue; // 不满足任一有效组合则跳过
                    }
                }
                //用来判断产品型谱第一次绑定时 是否绑定多个模板
                if (flag) {
                    if (forPartTypeName.equals(PRODUCTSPECTRUM) && PartTypeName.equals(STATUSNAME)){
                        flag = false;
                    }
                }else {
                    return ResponseResult.fail("500", "一个产品型谱只能绑定一个模板，请重新选择");
                }
                // 在这里判断模板状态是否为已发布
                if (!canExecute(PartTypeName,forPartTypeName,partDO,forPartDO)) {

                    // 如果不能执行，返回失败结果
                    return ResponseResult.fail("500", "模板未发布，不允许使用");
                }
                //通过编码获取已经绑定的替代件 判断是否已经绑定了模板
                try {
                    //主绑定的 替代件列表
                    List<AlternateInfoVO> forList = this.typlmPartAlternateService.batchQueryAlternates(Arrays.asList(alternateForNumber));
                    //被绑定的替代件列表
                    List<AlternateInfoVO> list = this.typlmPartAlternateService.batchQueryAlternates(Arrays.asList(alternateNumber));

                    //当使用产品型谱去绑定模板时  先判断产品型谱里面是否已经绑定了模板
                    if (forPartTypeName.equals(PRODUCTSPECTRUM) && forList != null
                            && !forList.isEmpty()&&PartTypeName.equals(STATUSNAME)) {
                        for (AlternateInfoVO alternateInfoVO : forList) {
                            PartDO part = typlmPdmPartService.queryLastPartDoByPartNumber(alternateInfoVO.getAlternateObjectNumber());
                            if (part.getTypeotype().equals(STATUSNAME)) {
                                return ResponseResult.fail("500", "该产品型谱已经绑定过模板，禁止绑定多个模板");
                            }
                        }
                    }

                    //当用模板绑定产品型谱时 ， 先判断产品型谱是否绑定了模板
                    if (forPartTypeName.equals(STATUSNAME) && list != null
                            && !list.isEmpty() && PartTypeName.equals(PRODUCTSPECTRUM)) {
                        for (AlternateInfoVO alternateInfoVO : list) {
                            PartDO part = typlmPdmPartService.queryLastPartDoByPartNumber(alternateInfoVO.getAlternateObjectNumber());
                            String partName = dspfStatusModuleitemMapper.selectTypeNNameByTypeoid(part.getTypeoid());
                            if (partName.equals(STATUSNAME)) {
                                return ResponseResult.fail("500", "选择的产品型谱存在与其他模板绑定的，请重新选择");
                            }
                        }
                    }


                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
                PartAlterLinkVO newVo1 = new PartAlterLinkVO();
                newVo1.setAlternateForNumber(vo.getAlternateForNumber());
                newVo1.setAlternateForOid(vo.getAlternateForOid());
                newVo1.setAlternateNumber(vo.getAlternateNumber());
                newVo1.setAlternateOid(vo.getAlternateOid());
                newVo1.setReplacementType("a");
                newParamList.add(newVo1);
                // 创建新的PartAlterLinkVO对象并添加到集合
                PartAlterLinkVO newVo = new PartAlterLinkVO();
                newVo.setAlternateForNumber(vo.getAlternateNumber());
                newVo.setAlternateForOid(vo.getAlternateOid());
                newVo.setAlternateNumber(vo.getAlternateForNumber());
                newVo.setAlternateOid(vo.getAlternateForOid());
                newVo.setReplacementType("a");
                Object o = updateDspfStatusModuleitem(newVo);
                if (o != null) {
                    return o;
                }
                newParamList.add(newVo);
                flag1 = false;
            }
            if (!flag1){
                // 构造新的参数数组
                Object[] newArgs = new Object[1];
                newArgs[0] = newParamList;
                // 继续执行原方法，传入新参数
                return joinPoint.proceed(newArgs);
            }
        }

        // 继续执行原方法
        return joinPoint.proceed();
    }

    // 自定义判断逻辑
    private boolean canExecute(String PartTypeName, String forPartTypeName, PartDO partDO,PartDO forPartDO) {

        //如果通过状态需求模板去绑定  则需要判断模板是否发布
        if (forPartDO != null && STATUSNAME.equals(forPartTypeName) &&forPartDO.getLifecyclestagekey().equals("RELEASED")){
            return true;
        }
        //如果通过产品型谱去绑定  则需要判断模板是否发布
        if (forPartDO != null && PRODUCTSPECTRUM.equals(forPartTypeName)&&partDO.getLifecyclestagekey().equals("RELEASED")){
            return true;
        }

        return false;
    }
    private Object updateDspfStatusModuleitem(PartAlterLinkVO vo) {
        boolean flag = true;
        // 主绑定
        String alternateForNumber = vo.getAlternateForNumber();
        //被绑定
        String alternateNumber = vo.getAlternateNumber();
        if (alternateNumber == null || alternateNumber.isEmpty()) {
            return false;
        }
        PartDO forPartDO = typlmPdmPartService.queryLastPartDoByPartNumber(alternateForNumber);
        PartDO partDO = typlmPdmPartService.queryLastPartDoByPartNumber(alternateNumber);
        String forPartTypeName = dspfStatusModuleitemMapper.selectTypeNNameByTypeoid(forPartDO.getTypeoid());
        String PartTypeName = dspfStatusModuleitemMapper.selectTypeNNameByTypeoid(partDO.getTypeoid());

        //用来判断产品型谱第一次绑定时 是否绑定多个模板
        if (flag) {
            if (forPartTypeName.equals(PRODUCTSPECTRUM) && PartTypeName.equals(STATUSNAME)){
                flag = false;
            }
        }else {
            return ResponseResult.fail("500", "一个产品型谱只能绑定一个模板，请重新选择");
        }
        // 在这里判断模板状态是否为已发布
        if (!canExecute(PartTypeName,forPartTypeName,partDO,forPartDO)) {

            // 如果不能执行，返回失败结果
            return ResponseResult.fail("500", "模板未发布，不允许使用");
        }
        //通过编码获取已经绑定的替代件 判断是否已经绑定了模板
        try {
            //主绑定的 替代件列表
            List<AlternateInfoVO> forList = this.typlmPartAlternateService.batchQueryAlternates(Arrays.asList(alternateForNumber));
            //被绑定的替代件列表
            List<AlternateInfoVO> list = this.typlmPartAlternateService.batchQueryAlternates(Arrays.asList(alternateNumber));

            //当使用产品型谱去绑定模板时  先判断产品型谱里面是否已经绑定了模板
            if (forPartTypeName.equals(PRODUCTSPECTRUM) && forList != null
                    && !forList.isEmpty()&&PartTypeName.equals(STATUSNAME)) {
                for (AlternateInfoVO alternateInfoVO : forList) {
                    PartDO part = typlmPdmPartService.queryLastPartDoByPartNumber(alternateInfoVO.getAlternateObjectNumber());
                    if (part.getTypeotype().equals(STATUSNAME)) {
                        return ResponseResult.fail("500", "该产品型谱已经绑定过模板，禁止绑定多个模板");
                    }
                }
            }

            //当用模板绑定产品型谱时 ， 先判断产品型谱是否绑定了模板
            if (forPartTypeName.equals(STATUSNAME) && list != null
                    && !list.isEmpty() && PartTypeName.equals(PRODUCTSPECTRUM)) {
                for (AlternateInfoVO alternateInfoVO : list) {
                    PartDO part = typlmPdmPartService.queryLastPartDoByPartNumber(alternateInfoVO.getAlternateObjectNumber());
                    String partName = dspfStatusModuleitemMapper.selectTypeNNameByTypeoid(part.getTypeoid());
                    if (partName.equals(STATUSNAME)) {
                        return ResponseResult.fail("500", "选择的产品型谱存在与其他模板绑定的，请重新选择");
                    }
                }
            }


        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        return null;
    }
}
